package com.cat.math;

import java.util.HashMap;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/most-frequent-prime/description/
 * @create 2025/10/15 20:29
 * @since JDK17
 */

public class Solution06 {
    static int[][] dire = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}};

    boolean judge(int n) {
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return n > 9;
    }

    public int mostFrequentPrime(int[][] mat) {
        int n = mat.length, m = mat[0].length, ans = -1, cnt = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                for (int[] d : dire) {  //
                    int x = i, y = j, cur = 0;
                    while (true) {
                        cur = cur * 10 + mat[x][y];
                        if (judge(cur)) {
                            map.merge(cur, 1, Integer::sum);
                        }
                        int nx = x + d[0], ny = y + d[1];
                        if (nx < 0 || nx >= n || ny < 0 || ny >= m) {
                            break;
                        }
                        x = nx;
                        y = ny;
                    }
                }
            }
        }
        for (var e : map.entrySet()) {
            if (e.getValue() > cnt || (e.getValue() == cnt && e.getKey() > ans)) {
                cnt = e.getValue();
                ans = e.getKey();
            }
        }
        return ans;
    }
}
